﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Net;
using BookForm.cls;
namespace BookForm.cls
{
    class WEBFunc
    {
        private static object _lockAddCookieobject = new object();

        public static HttpWebRequest CreateWebRequest(string URL)
        {
            return CreateWebRequest(URL, string.Empty, string.Empty, null);
        }
        public static HttpWebRequest CreateWebRequest(string URL, string strReferer, string PostData, System.Text.Encoding encoding)
        {
            Uri URI = new Uri(URL);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI);
            request.KeepAlive = false;
            request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
            if (strReferer.Length == 0)
            {
                request.Referer = "http://www.52mtg.com/bbs/logging.php?action=login";
            }
            else
            {
                request.Referer = strReferer;
            }
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";

            //设置代理
            if (Setting.UseProxy)
            {
                if (!Setting.IEProxy)
                {
                    WebProxy proxy = new WebProxy();

                    try
                    {
                        proxy.Address = new Uri(String.Format("http://{0}:{1}", Setting.ProxyServer, Setting.ProxyPort));
                        if (Setting.ProxyUsername.Length > 0 && Setting.ProxyPassword.Length > 0)
                        {
                            proxy.Credentials = new NetworkCredential(Setting.ProxyUsername, Setting.ProxyPassword);
                        }
                        request.Proxy = proxy;
                    }
                    catch
                    {

                    }
                }
            }
            else
            {
                request.Proxy = null;
            }

            //设置cookie
            if (Variant.CurrentUser != null)
            {
                if (request.CookieContainer == null)
                {
                    request.CookieContainer = new CookieContainer();
                }
                lock (_lockAddCookieobject)
                {
                    CookieCollection tmpCookies = Variant.CurrentUser.Cookies;


                    foreach (System.Net.Cookie cookie in tmpCookies)
                    {
                        cookie.Domain = URI.Host;
                        if (cookie.Value.Length != 0)
                        {
                            request.CookieContainer.Add(cookie);
                        }
                        else
                        {
                            //Console.WriteLine(cookie.ToString());
                        }
                    }
                }

            }



            //提交的数据
            if (PostData != null && PostData.Length > 0)
            {
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";


                byte[] b;
                if (encoding != null)
                {
                    b = encoding.GetBytes(PostData);
                }
                else
                {
                    b = Variant.encoding.GetBytes(PostData);
                }
                request.ContentLength = b.Length;
                using (System.IO.Stream sw = request.GetRequestStream())
                {
                    try
                    {

                        sw.Write(b, 0, b.Length);
                    }
                    catch
                    {
                        return null;
                    }
                    finally
                    {
                        //if (sw != null) { sw.Close(); }
                    }
                }

            }
            return request;
        }

        public static HttpWebRequest CreateWebRequest_(string URL, string strReferer, string PostData, System.Text.Encoding encoding)
        {
            Uri URI = new Uri(URL);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI);
            request.KeepAlive = false;
            request.Accept = "";
            if (strReferer.Length == 0)
            {
                request.Referer = "http://www.52mtg.com/bbs/logging.php?action=login";
            }
            else
            {
                request.Referer = strReferer;
            }
            request.UserAgent = "";

            //设置代理
            if (Setting.UseProxy)
            {
                if (!Setting.IEProxy)
                {
                    WebProxy proxy = new WebProxy();

                    try
                    {
                        proxy.Address = new Uri(String.Format("http://{0}:{1}", Setting.ProxyServer, Setting.ProxyPort));
                        if (Setting.ProxyUsername.Length > 0 && Setting.ProxyPassword.Length > 0)
                        {
                            proxy.Credentials = new NetworkCredential(Setting.ProxyUsername, Setting.ProxyPassword);
                        }
                        request.Proxy = proxy;
                    }
                    catch
                    {

                    }
                }
            }
            else
            {
                request.Proxy = null;
            }

            //设置cookie
            if (Variant.CurrentUser != null)
            {
                if (request.CookieContainer == null)
                {
                    request.CookieContainer = new CookieContainer();
                }
                lock (_lockAddCookieobject)
                {
                    CookieCollection tmpCookies = Variant.CurrentUser.Cookies;


                    foreach (System.Net.Cookie cookie in tmpCookies)
                    {
                        cookie.Domain = URI.Host;
                        if (cookie.Value.Length != 0)
                        {
                            request.CookieContainer.Add(cookie);
                        }
                        else
                        {
                            //Console.WriteLine(cookie.ToString());
                        }
                    }
                }

            }



            //提交的数据
            if (PostData != null && PostData.Length > 0)
            {
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";


                byte[] b;
                if (encoding != null)
                {
                    b = encoding.GetBytes(PostData);
                }
                else
                {
                    b = Variant.encoding.GetBytes(PostData);
                }
                request.ContentLength = b.Length;
                using (System.IO.Stream sw = request.GetRequestStream())
                {
                    try
                    {

                        sw.Write(b, 0, b.Length);
                    }
                    catch
                    {
                        return null;
                    }
                    finally
                    {
                        //if (sw != null) { sw.Close(); }
                    }
                }

            }
            return request;
        }

        public static String GetSyncHTML(WebRequest request, System.Text.Encoding encoding)
        {
            Stream dataStream = GetStream(request);
            string strHtml = string.Empty;
            System.IO.StreamReader sr = null;
            try
            {

                sr = new System.IO.StreamReader(dataStream, encoding != null ? encoding : Variant.encoding);
                strHtml = sr.ReadToEnd();
            }
            finally
            {
                if (sr != null) { sr.Close(); }
            }
            return strHtml;
        }

        public static Stream GetStream(WebRequest request)
        {
            MemoryStream dataStream;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (Variant.CurrentUser != null)
            {
                AddCookies(response.Cookies);
            }
            try
            {
                dataStream = CopyStream(response.GetResponseStream());
            }
            finally
            {
                request.Abort();
                response.Close();
            }
            return dataStream;
        }

        private static MemoryStream CopyStream(Stream stream)
        {
            MemoryStream result = new MemoryStream();
            byte[] buffer = new byte[0x1000];
            while (true)
            {
                int size = stream.Read(buffer, 0, 0x1000);
                if (size <= 0)
                {
                    break;
                }
                result.Write(buffer, 0, size);
            }
            result.Seek(0L, SeekOrigin.Begin);
            return result;
        }


        private static void AddCookies(CookieCollection newCookies)
        {
            lock (_lockAddCookieobject)
            {

                if (newCookies.Count == 0)
                {
                    return;
                }
                CookieCollection tmpCookies = new CookieCollection();
                CookieCollection oldCookies = Variant.CurrentUser.Cookies;

                bool blnExist;
                foreach (System.Net.Cookie newcookie in newCookies)
                {

                    tmpCookies.Add(newcookie);
                }
                foreach (System.Net.Cookie oldcookie in oldCookies)
                {

                    blnExist = false;
                    foreach (System.Net.Cookie newcookie in tmpCookies)
                    {
                        if (newcookie.Name.Equals(oldcookie.Name))
                        {
                            blnExist = true;
                            break;
                        }
                    }
                    if (!blnExist)
                    {
                        tmpCookies.Add(oldcookie);
                    }
                }

                Variant.CurrentUser.Cookies = tmpCookies;
            }

        }
    }
}
